package com.tsd.base.controller;

import com.alibaba.fastjson.JSON;
import com.tsd.base.entity.BasePrinter;
import com.tsd.base.entity.BasePrinterExt;
import com.tsd.base.service.BasePrinterService;
import com.tsd.core.utils.XpYunPrinterUtil;
import com.tsd.common.controller.BaseController;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.HttpResult;
import com.tsd.core.vo.PageBean;
import com.tsd.system.entity.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：BasePrinter打印机 控制层
 *
 * @author david
 * @date 2022/05/12 09:38:04
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
@Api(tags = "基础-打印机", description = "打印机的API描述")
public class BasePrinterController extends BaseController {

    @Resource
    private BasePrinterService basePrinterService;

    @ApiOperation(value = "根据sid获取打印机", notes = "根据sid获取打印机")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sid", value = "打印机sid", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/getBasePrinterBySid.action", method = RequestMethod.POST)
    public HttpResult<BasePrinter> getBasePrinterBySid() {
        HttpResult<BasePrinter> hr = new HttpResult<BasePrinter>();
        try {
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, "sid");
            super.checkEmpty(sid, "请提供参数sid");
            BasePrinter basePrinter = basePrinterService.queryBySid(sid);
            hr.setData(basePrinter);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据id删除打印机", notes = "根据id删除打印机")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sids", value = "打印机sids", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/deleteBasePrinters.action", method = RequestMethod.POST)
    public HttpResult<Object> deleteBasePrinters() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Object sids = map.get("sids");
            super.checkEmpty(sids, "请提供参数sids");
            List<String> list = JSON.parseArray(JSON.toJSONString(sids), String.class);
            for (String sid : list) {
                BasePrinterExt t = basePrinterService.queryBySid(sid);
                if (t != null) {
                    if (t.getState() == null || t.getState().equals(BasePrinterExt.STATE_HAS_REG3RD)) {
                        if (BasePrinterExt.PRINTER_BRAND_XPYUN.equals(t.getBrand())) {
                            HttpResult<Object> hr2 = XpYunPrinterUtil.delXpYunPrinter(t.getCode());
                            if (hr2.getCode() == ErrorCode.CODE_SUCCESS) {
                                t.setState(BasePrinterExt.STATE_NOT_REG3RD);
                                basePrinterService.saveBasePrinter(t, opUser);
                            } else {
                                throw new HlpException("从第三方平台删除打印机出错" + hr2.getMessage());
                            }
                        }
                    }
                }
            }
            basePrinterService.deleteBasePrinters(list, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }


    @ApiOperation(value = "保存打印机", notes = "保存打印机，具有id值则更新，没有id值则新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "obj", value = "打印机", required = true, paramType = "body", dataType = "BasePrinter")
    })
    @ResponseBody
    @RequestMapping(value = "/saveBasePrinter.action", method = RequestMethod.POST)
    public HttpResult<Object> saveBasePrinter() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String json = JSON.toJSONString(map);
            BasePrinter t = JSON.parseObject(json, BasePrinter.class);
            basePrinterService.saveBasePrinter(t, opUser);
            if (t.getState() == null || !t.getState().equals(BasePrinterExt.STATE_HAS_REG3RD)) {
                if (BasePrinterExt.PRINTER_BRAND_XPYUN.equals(t.getBrand())) {
                    HttpResult<Object> hr2 = XpYunPrinterUtil.regXpYunPrinter(t.getCode(), t.getName());
                    if (hr2.getCode() == ErrorCode.CODE_SUCCESS) {
                        t.setState(BasePrinterExt.STATE_HAS_REG3RD);
                        basePrinterService.saveBasePrinter(t, opUser);
                    }
                    hr2.setData(t);
                    return hr2;
                }
            }
            hr.setData(t);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询打印机", notes = "分页查询打印机")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", required = false, dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/findBasePrinters.action", method = RequestMethod.POST)
    public HttpResult<List<BasePrinterExt>> findBasePrinters() {
        HttpResult<List<BasePrinterExt>> hr = new HttpResult<List<BasePrinterExt>>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>();
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", true, 0);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            PageBean page = new PageBean(map);
            List<BasePrinterExt> list = basePrinterService.findBasePrinters(params, page);
            if (list != null && list.size() > 0) {
                if (BasePrinterExt.PRINTER_BRAND_XPYUN.equals(list.get(0).getBrand())) {
                    List<String> snList = new ArrayList<>();
                    for (BasePrinterExt t : list) {
                        //防止list中的code有重复的情况采用此方法
                        snList.add(t.getCode());
                    }
                    List<Integer> stateList = XpYunPrinterUtil.queryPrintersStatus(snList);
                    if (stateList != null && stateList.size() == list.size()) {
                        for (int i = 0; i < list.size(); i++) {
                            BasePrinterExt t = list.get(i);
                            Integer st = stateList.get(i);
                            String status = st == 1 ? "在线正常" : (st == 2 ? "在线缺纸" : "离线");
                            t.setOn_status(status);
                        }
                    }
                }
            }
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
}
